#include <memory>
#include <cstdlib>
#include "seacher.hpp"
#include "cpp-httplib-v0.7.15/httplib.h"

const std::string root_path = "./wwwroot";

void Usage(const std::string proc)
{
    std::cout << "Usage: " << proc << " " << "[port]" << std::endl; 
}

int main(int argc, char* argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(0);
    }
    int port = atoi(argv[1]);

    std::shared_ptr<Seacher> searcher = std::make_shared<Seacher>();
    searcher->InitSeacher();
    httplib::Server svr;
    svr.set_base_dir(root_path.c_str());
    svr.Get("/s", [&searcher](const httplib::Request &req, httplib::Response &res) 
    {
        if (!req.has_param("word"))
        {
            res.set_content("必须要有搜索关键字!", "text/plain; charset=utf-8");
            return;
        }
        std::string key = req.get_param_value("word");
        std::string json_string;
        searcher->Search(key, &json_string);
        res.set_content(json_string, "application/json");
        lg(Info, "收到客户端请求,客户搜索关键词为:%s\n", key.c_str());
    });

    lg(Info, "服务器启动成功\n");
    
    svr.listen("0.0.0.0", port);
    return 0;
}